﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MailSharp
{
  public class TemplateInfo
  {
    public string FileName;
    public string Content;
    public List<string> ImageFileNames;

    public static TemplateInfo LoadFromFile(string fileFullPath)
    {
      TemplateInfo retVal = new TemplateInfo();
      try
      {
        retVal.Content = System.IO.File.ReadAllText(fileFullPath);
      }
      catch (Exception ex)
      {
        throw new Exception("MailSharp could not read template from " + fileFullPath, ex);
      }

      // 
      // Regular expression courtesy of http://regexlib.com/REDetails.aspx?regexp_id=1397
      //
      System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex("<img[^>]* src=\"([^\"]*)\"[^>]*>");
      System.Text.RegularExpressions.MatchCollection matches;
      matches = rex.Matches(retVal.Content);
      List<string> imageList = new List<string>();

      foreach (System.Text.RegularExpressions.Match m in matches)
      {
        imageList.Add(m.Groups[1].Captures[0].Value);
      }

      for (int i = 0; i < imageList.Count; i++)
      {
        string pattern = "<img[^>]* src=\"" + imageList[i]  + "\"[^>]*>";
        retVal.Content = System.Text.RegularExpressions.Regex.Replace(retVal.Content, pattern, "<img src=\"cid:img" + i.ToString() + "\" />");
      }

      retVal.ImageFileNames = imageList;

      return retVal;
    }

  }
}
